package com.cyx.netty.n5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/*
Netty Hello World !
a-b-c-d-e-f-g-h-i-j-k-l-m-n
 */
public class HelloServer {
    public static void main(String[] args) {
        // 1.启动器，负责组装Netty组件，启动服务器 [a]
        new ServerBootstrap()
                // 2.加入EventLoop组 [b]
                .group(new NioEventLoopGroup())
                // 3.选择服务器的ServerSocketChannel实现 [c]
                .channel(NioServerSocketChannel.class)
                // 4.决定将来能执行哪些操作（handler） [d]
                .childHandler(new ChannelInitializer<NioSocketChannel>() { // 5.channel代表和客户端进行数据读写的通道Initializer初始化，负责添加别的handler
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 6.添加具体handler [k]
                        ch.pipeline().addLast(new StringDecoder()); // 将ByteBuf转换为字符串
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){ // 自定义handler
                            @Override // 读事件
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                // 打印上一步转换好的字符串 [n]
                                System.out.println(msg);
                            }
                        });
                    }
                })
                // 7.绑定监听端口 [e]
                .bind(8888);
    }
}
